package chapter3

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	Name string `form:"name"`
	Age  int    `form:"age"`
}

func Temp(ctx *gin.Context) {
	// arr := [3]int{1, 2, 3}
	user := &UserInfo{
		"xiaofang",
		11,
	}
	arr := [3]int{1, 2, 3}
	username := [3]string{"xiaofang", "xiaowu", "xiaoxue"}
	val := map[string]interface{}{
		"arr":      arr,
		"struct":   user,
		"username": username,
	}
	ctx.HTML(200, "/chapter3/template.html", val)
}

func Add(a int, b int) int {
	return a + b
}

func TimeTransfer() int64 {
	time_int := time.Now().Unix()
	return time_int
}

func ToForm(ctx *gin.Context) {
	ctx.HTML(200, "/chapter3/form.html", nil)
}

func PostForm(ctx *gin.Context) {
	var user UserInfo
	ctx.ShouldBind(&user)
	ctx.String(200, "user name:%s", user.Name)
}

func BindQuery(ctx *gin.Context) {
	var user UserInfo
	ctx.ShouldBind(&user)
	ctx.String(200, "user name:%s", user.Name)
}

func ToJson(ctx *gin.Context) {
	ctx.HTML(200, "/chapter3/json.html", nil)
}

func GetJson(ctx *gin.Context) {
	var user UserInfo
	ctx.ShouldBind(&user)
	ctx.JSON(200, gin.H{
		"code": 200,
		"ok":   "ok",
	})
}

// type ValidUser struct {
// 	Name   string `form:"name" binding:"required"`
// 	Age    int    `form:"age" binding:"min=5"`
// 	Addres string `form:"addr" binding:"max=10"`
// }

type ValidUser struct {
	Name   string `form:"name" valid:"Required"`
	Age    int    `form:"age" valid:"Min=5"`
	Addres string `form:"addr" valid:"Max=10"`
}

func ToVAalid(ctx *gin.Context) {
	ctx.HTML(200, "/chapter3/valid.html", nil)
}

func GetValid(ctx *gin.Context) {
	var user ValidUser
	err := ctx.ShouldBind(&user)
	if err != nil {
		fmt.Printf("err info:%s", err)
	}

	ctx.String(200, "成功 userInfo:%s", user.Name)
}
